package com.jy.project.job;
import com.jy.project.constant.MaterialConstant;
import com.jy.project.domain.*;
import com.jy.project.enums.ApplyTypeEnum;
import com.jy.project.enums.ApplyTypeMatericalEnum;
import com.jy.project.enums.DoTaskEnum;
import com.jy.project.mapper.*;
import com.jy.project.util.RedisUtils;
import com.jy.project.vo.MaterialVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@EnableScheduling
@Component
@Slf4j
public class ToDoTasksJob {

    @Autowired
    private  ApplyMapper applyMapper;

    @Autowired
    private ToDoTasksMapper toDoTasksMapper;

    @Autowired
    private SignMapper signMapper;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private MaterialMapper materialMapper;

    @Scheduled(cron = "*/4 * * * * ?")
    public void scanBill(){
        init();
    }

    private synchronized void init(){
        List<Apply> list = listApply();
        for (Apply apply : list) {
            Integer applyType = apply.getApplyType();
            try {
                if (applyType.equals(ApplyTypeEnum.INSERT_MATERIAL.getCode())){
                    businessInsertSevice(apply);
                }
                if (applyType.equals(ApplyTypeEnum.COLLECT.getCode())){
                    businessCollectSevice(apply);
                }

                if (applyType.equals(ApplyTypeEnum.STOCK_RETURN.getCode())){
                    businessStockReturn(apply);
                }


            }catch (Exception e){
                if (e instanceof DuplicateKeyException){

                }else {
                    e.printStackTrace();
                }

            }

        }
    }
    public List<Apply> listApply(){
        LocalDateTime dateTime = LocalDateTime.now();
        LocalDateTime startTime = LocalDateTime.of(dateTime.getYear(), dateTime.getMonthValue(), dateTime.getDayOfMonth(), 0, 0,0);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String startFormat = startTime.format(formatter);
        LocalDateTime endTime = LocalDateTime.of(dateTime.getYear(), dateTime.getMonthValue(), dateTime.getDayOfMonth(), 23, 59,59);
        String endFormat = endTime.format(formatter);
        Example example=new Example(Apply.class);
        example.createCriteria()
                .andGreaterThanOrEqualTo("createAt",startFormat )
                .andLessThanOrEqualTo("createAt",endFormat );
        List<Apply> applies = applyMapper.selectByExample(example);
        return  applies;
    }




    private ToDoTasks createToDoTasks(Apply apply){
        ToDoTasks tasks=new ToDoTasks();
        BeanUtils.copyProperties(apply,tasks);
        Date date = new Date();
        tasks.setId(null);
        tasks.setSortNum(1);
        tasks.setCreateAt(date);
        tasks.setUpdateAt(date);
        tasks.setIsDelete(0);
        Long applicantUserId=  apply.getApplicantUserId();
        tasks.setCreateUserId(applicantUserId);
        return  tasks;
    }



    private void businessInsertSevice(Apply apply){
        String applyNo = apply.getApplyNo();
        ToDoTasks doTasks = toDoTasksMapper.getDoTasks(applyNo);
        if (doTasks==null){
            ToDoTasks toDoTasks = createToDoTasks(apply);
            toDoTasks.setSortNum(1);
            toDoTasks.setIsEnd(0);
            toDoTasks.setStatus(DoTaskEnum.CRTEATED.getCode());
            toDoTasksMapper.insertSelective(toDoTasks);
            Long createUserId = toDoTasks.getCreateUserId();
            if (createUserId!=null&&createUserId!=0){
                Sign sign=createSign(toDoTasks,toDoTasks.getCreateUserId(),createUserId);
                sign.setStatus(DoTaskEnum.AGREE.getCode());
                signMapper.insert(sign);
            }
            Long useUserId = toDoTasks.getUseUserId();
            if (useUserId!=null&&useUserId!=0){
              Sign sign=createSign(toDoTasks,toDoTasks.getCreateUserId(),useUserId);
                sign.setStatus(DoTaskEnum.CRTEATED.getCode());

                signMapper.insert(sign);
            }
            Long managementUserId = toDoTasks.getManagementUserId();
            if (managementUserId!=null&&managementUserId!=0){
                Sign sign=createSign(toDoTasks,toDoTasks.getCreateUserId(),managementUserId);
                sign.setStatus(DoTaskEnum.CRTEATED.getCode());
                signMapper.insert(sign);
            }
        }

    }

    private Sign createSign(ToDoTasks tasks,Long userId,Long childUserId){
        Sign sign=new Sign();
        sign.setStatus(0);
        sign.setType(0);
        if (userId!=null) {
            sign.setUserId(userId);
            User user = userMapper.selectByPrimaryKey(userId);
            sign.setUserNickName(user.getNickName());
        }
       if (childUserId!=null) {
           sign.setChildUserId(childUserId);
           User childUser = userMapper.selectByPrimaryKey(childUserId);
           sign.setChildNicKName(childUser.getNickName());
       }
        sign.setApplyNo(tasks.getApplyNo());
        sign.setCreateAt(new Date());
        sign.setUpdateDay(new Date());
        sign.setIsDelete(0);
        sign.setUpdateAt(new Date());
        return  sign;
    }

    private void businessCollectSevice(Apply apply){
        String applyNo = apply.getApplyNo();
        ToDoTasks doTasks = toDoTasksMapper.getDoTasks(applyNo);
        if (doTasks==null){
            ToDoTasks toDoTasks = createToDoTasks(apply);
            toDoTasks.setSortNum(1);
            toDoTasks.setIsEnd(0);
            toDoTasks.setStatus(DoTaskEnum.CRTEATED.getCode());
            boolean isSystem= applyNo.startsWith(ApplyTypeMatericalEnum.SYSTEM_COLLECT.getValue());
            if (isSystem){
                toDoTasks.setStatus(DoTaskEnum.AGREE.getCode());
                toDoTasks.setIsEnd(1);
            }
            toDoTasksMapper.insertSelective(toDoTasks);
            Long createUserId = toDoTasks.getCreateUserId();
            if (createUserId!=null&&createUserId!=0){
                Sign sign=createSign(toDoTasks,toDoTasks.getCreateUserId(),createUserId);
                sign.setStatus(DoTaskEnum.AGREE.getCode());
                signMapper.insert(sign);
            }
            Long useUserId = toDoTasks.getUseUserId();
            if (useUserId!=null&&useUserId!=0){
                Sign sign=createSign(toDoTasks,toDoTasks.getCreateUserId(),useUserId);
                sign.setStatus(DoTaskEnum.CRTEATED.getCode());
                if (isSystem){
                    sign.setStatus(DoTaskEnum.AGREE.getCode());
                }
                signMapper.insert(sign);
            }
            Long managementUserId = toDoTasks.getManagementUserId();
            if (managementUserId!=null&&managementUserId!=0){
                Sign sign=createSign(toDoTasks,toDoTasks.getCreateUserId(),managementUserId);
                sign.setStatus(DoTaskEnum.CRTEATED.getCode());
                if (isSystem){
                    sign.setStatus(DoTaskEnum.AGREE.getCode());
                }
                signMapper.insert(sign);
            }
            if (isSystem) {
                Apply applyDTO=new Apply();
                Long id = apply.getId();
                applyDTO.setId(id);
                applyDTO.setStatus(1);
                applyMapper.updateByPrimaryKeySelective(applyDTO);
                String materialNo = apply.getMaterialNo();
                MaterialVO materialVO = materialMapper.getMaterialVO(materialNo);
                Long mId = materialVO.getId();
                Material material=new Material();
                material.setId(mId);
                material.setUseStatus(1);
                material.setStatus(0);
                materialMapper.updateByPrimaryKeySelective(material);
            }

        }

    }

    private void businessStockReturn(Apply apply){
        String applyNo = apply.getApplyNo();
        ToDoTasks doTasks = toDoTasksMapper.getDoTasks(applyNo);
        if (doTasks==null){
            ToDoTasks toDoTasks = createToDoTasks(apply);
            toDoTasks.setSortNum(1);
            toDoTasks.setIsEnd(0);
            toDoTasks.setStatus(DoTaskEnum.CRTEATED.getCode());
            toDoTasksMapper.insertSelective(toDoTasks);
            Long createUserId = toDoTasks.getCreateUserId();
            if (createUserId!=null&&createUserId!=0){
                Sign sign=createSign(toDoTasks,toDoTasks.getCreateUserId(),createUserId);
                sign.setStatus(DoTaskEnum.AGREE.getCode());
                signMapper.insert(sign);
            }
            Long useUserId = toDoTasks.getUseUserId();
            if (useUserId!=null&&useUserId!=0){
                Sign sign=createSign(toDoTasks,toDoTasks.getCreateUserId(),useUserId);
                sign.setStatus(DoTaskEnum.CRTEATED.getCode());
                signMapper.insert(sign);
            }
            Long managementUserId = toDoTasks.getManagementUserId();
            if (managementUserId!=null&&managementUserId!=0){
                Sign sign=createSign(toDoTasks,toDoTasks.getCreateUserId(),managementUserId);
                sign.setStatus(DoTaskEnum.CRTEATED.getCode());
                signMapper.insert(sign);
            }

        }

    }



}
